<script lang="ts" setup>
import api from "@/api";
import { type PageDTO, type MachineDTO, MachinePageQry } from "@/types";
import { computed, onMounted, ref, watch } from "vue";
import { nanoid } from 'nanoid';

const props = defineProps({
  value: String,
  id: String
});

const emit = defineEmits(["update:value"]);

const value = computed({
  get() {
    return props.value;
  },
  set(val) {
    emit("update:value", val);
  }
});


const getDefaultResult = (): PageDTO<MachineDTO> => {
  return {
    current: 1,
    data: [],
    size: 10,
    totalPage: 0,
    totalSize: 0
  };
};

const qry = ref<MachinePageQry>(new MachinePageQry());
const result = ref<PageDTO<MachineDTO>>(getDefaultResult());
const loading = ref(false);

const loadData = () => {
  loading.value = true;
  api.machine
    .getMachinePage(qry.value)
    .then((res) => {
      result.value.current = res.data.current;
      result.value.size = res.data.size;
      result.value.totalPage = res.data.totalPage;
      result.value.totalSize = res.data.totalSize;
      result.value.data.push(...res.data.data);
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleSearch = (val: string) => {
  qry.value = new MachinePageQry();
  qry.value.nameLike = val;
  result.value = getDefaultResult();
  loadData();
};

const loadMore = () => {
  qry.value.current++;
  loadData();
};

watch(
  () => props.id,
  (oldVal, newVal) => {
    result.value = getDefaultResult();
    qry.value.current = 1;
    qry.value.id = oldVal;
    loadData();
  }
);

const uid = ref("single-select-loadmore");

onMounted(() => {
  uid.value = nanoid();
  if(!props.id){
    loadData();
  }
});
</script>

<template>
  <el-select :data-loadmore="uid"
    v-model="value"
    v-load-more="loadMore"
    v-bind="$attrs"
    filterable
    :popper-class="uid"
    :filter-method="handleSearch"
  >
    <el-option v-for="item in result.data" :key="item.id" :label="item.name" :value="item.id">
      <span style="float: left">{{ item.name }}</span>
      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
        {{ item.groupName }}
      </span>
    </el-option>
    <el-option disabled v-loading="loading" v-show="loading" value="-1"></el-option>
  </el-select>
</template>
